import { RES_ERROR, Tab_status } from '@/config/env'
import { TableType } from '@/config/types'
import UseList from '@/hooks/getList'
import { P1AlarmInfo } from '@/service/api'
import { message } from 'antd'
import React, { useContext, useEffect, useState } from 'react'
import { useGlobalContext } from './GlobalContext'
interface TableContextType {
  receiverName: string
  spinning: boolean

  businessTableList: P1AlarmInfo[]
  businessIndex: number
  businessCount: number

  maintenanceTableList: P1AlarmInfo[]
  maintenanceIndex: number
  maintenanceCount: number

  onChangeTab: (type: TableType, key: string) => void
  queryList: (name?: string) => Promise<string>
  onChangePageIndex: (type: TableType, index: number) => void
  onReset: () => void
}
const TableContext = React.createContext<TableContextType | null>(null)

export const TableProvider: React.FC<{
  children: React.ReactNode
}> = ({ children }) => {
  const { isUpdate, setIsUpdate } = useGlobalContext()
  const { getBusinessList, getMaintenanceList, getAllList } = UseList()
  const [messageApi] = message.useMessage()

  const [spinning, setSpinning] = React.useState(false)

  const [receiverName, setReceiverName] = useState('')
  const [businessPhoneAnsweredFlag, setBusinessPhoneAnsweredFlag] = useState(-1)
  const [businessIndex, setBusinessIndex] = useState(1)
  const [businessTableList, setBusinessTableList] = useState<P1AlarmInfo[]>([])
  const [businessCount, setBusinessCount] = useState(0)

  const [maintenancePhoneAnsweredFlag, setMaintenancePhoneAnsweredFlag] =
    useState(-1)
  const [maintenanceIndex, setMaintenanceIndex] = useState(1)
  const [maintenanceTableList, setMaintenanceTableList] = useState<
    P1AlarmInfo[]
  >([])
  const [maintenanceCount, setMaintenanceCount] = useState(0)

  useEffect(() => {
    if (isUpdate) {
      //todo 当前页是第一页的时候才刷新,其他页面不刷新，防止影响操作
      if (businessIndex === 1 && maintenanceIndex === 1 && !receiverName) {
        queryList()
      }
    }
  }, [isUpdate])
  const onChangeTab = async (type: TableType, key: string) => {
    const curKey = key as keyof typeof Tab_status
    const phoneAnsweredFlag = Tab_status[curKey]
    const params = {
      phoneAnsweredFlag,
      receiverName,
      pageIndex: 1,
    }
    setSpinning(true)
    try {
      if (type === 'business') {
        setBusinessPhoneAnsweredFlag(Tab_status[curKey])
        setBusinessIndex(params.pageIndex)
        const { code, data, msg } = await getBusinessList(params)

        if (code === 200) {
          setBusinessTableList(data.alarmInfoVos)
          setBusinessCount(data.amount)
        }
      } else {
        setMaintenancePhoneAnsweredFlag(Tab_status[curKey])
        setMaintenanceIndex(params.pageIndex)
        const { code, data, msg } = await getMaintenanceList(params)
        if (code === 200) {
          console.log('getMaintenanceList', code, data, msg)

          setMaintenanceTableList(data.alarmInfoVos)
          setMaintenanceCount(data.amount)
        }
      }
    } catch (err) {
      console.error(err)
    } finally {
      setSpinning(false)
    }
  }

  const onChangePageIndex = async (type: TableType, index: number) => {
    setSpinning(true)
    try {
      if (type === 'business') {
        setBusinessIndex(index)
        const res = await getBusinessList({
          receiverName,
          phoneAnsweredFlag: businessPhoneAnsweredFlag,
          pageIndex: index,
        })
        setBusinessTableList(res.data.alarmInfoVos)
        setBusinessCount(res.data.amount)
      } else {
        setMaintenanceIndex(index)
        const res = await getMaintenanceList({
          receiverName,
          phoneAnsweredFlag: maintenancePhoneAnsweredFlag,
          pageIndex: index,
        })
        setMaintenanceTableList(res.data.alarmInfoVos)
        setMaintenanceCount(res.data.amount)
      }
    } catch (error) {
      console.error(error)
    } finally {
      setSpinning(false)
    }
  }
  const queryList = async (name?: string) => {
    const curName = name || receiverName
    setSpinning(true)
    setReceiverName(curName)
    try {
      const res = await Promise.allSettled([
        getBusinessList({
          receiverName: curName,
          phoneAnsweredFlag: businessPhoneAnsweredFlag,
          pageIndex: businessIndex,
        }),
        getMaintenanceList({
          receiverName: curName,
          phoneAnsweredFlag: maintenancePhoneAnsweredFlag,
          pageIndex: maintenanceIndex,
        }),
      ])

      if (res.some(item => item.status === 'rejected')) {
        messageApi.open({
          type: 'error',
          content: RES_ERROR,
        })
      }
      const [businessRes, mainTenanceRes] = res
      if (businessRes.status === 'fulfilled') {
        setBusinessTableList(businessRes.value.data.alarmInfoVos)
        setBusinessCount(businessRes.value.data.amount)
      }
      if (mainTenanceRes.status === 'fulfilled') {
        setMaintenanceTableList(mainTenanceRes.value.data.alarmInfoVos)
        setMaintenanceCount(mainTenanceRes.value.data.amount)
      }
      return Promise.resolve('success')
    } catch (error) {
      return Promise.reject(RES_ERROR)
    } finally {
      setSpinning(false)
      // 重置更新
      if (isUpdate) {
        setIsUpdate(false)
      }
    }
  }
  async function onReset() {
    setBusinessIndex(1)
    setMaintenanceIndex(1)
    setReceiverName('')
    const res = await getAllList({
      receiverName: '',
      phoneAnsweredFlag: -1,
      pageIndex: 1,
    })
    if (res.some(item => item.status === 'rejected')) {
      messageApi.open({
        type: 'error',
        content: '服务存在异常，请刷新重试或者联系管理员～',
      })
    }
    const [businessRes, mainTenanceRes] = res
    if (businessRes.status === 'fulfilled') {
      setBusinessTableList(businessRes.value.data.alarmInfoVos)
      setBusinessCount(businessRes.value.data.amount)
    }
    if (mainTenanceRes.status === 'fulfilled') {
      setMaintenanceTableList(mainTenanceRes.value.data.alarmInfoVos)
      setMaintenanceCount(mainTenanceRes.value.data.amount)
    }
  }
  return (
    <TableContext.Provider
      value={{
        receiverName,
        spinning,

        businessTableList,
        businessIndex,
        businessCount,

        maintenanceTableList,
        maintenanceIndex,
        maintenanceCount,

        onChangeTab,
        onChangePageIndex,
        queryList,
        onReset,
      }}
    >
      {children}
    </TableContext.Provider>
  )
}

export const useTableContext = (): TableContextType => {
  const context = useContext(TableContext)
  if (!context) {
    throw new Error('useTableContext must be used within a ThemeProvider')
  }
  return context
}

export default TableContext
